<?php
/**
 * StockAgg.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/27- 12:28 下午
 */

namespace common\models\es\dataProvider\comProducts;
use Yii;

class AggByStoreId extends Agg implements AggInterFace
{
    protected $storeIds= [];



    public function __construct(int $uid, int $mall_id,array $storeIds)
    {
        parent::__construct($uid, $mall_id);


        $this->storeIds = $storeIds;
    }

    /**
     * 获取数据
     * @return array
     */
    public function getData(): array
    {
        $params = [
            'index' => $this->getIndexName(),
            'body' => $this->getBody()
        ];
//        print_r(json_encode($this->getBody())); exit;
        $esResult = Yii::$app->elasticsearch->search($params);
        return $esResult['aggregations']['storeGroup']['buckets'] ?? [];
    }


    public function getBaseBody()
    {
        return  [
            'size' => 0,
            'query' => [
                'bool'=>[
                    'filter'=>$this->getFilter()
                ],
            ],
            'aggs' => [
                'storeGroup' => [
                    'terms' => [
                        'field' => 'store_id',
                        'size' => count($this->storeIds)
                    ]
                ]
            ]
        ];
    }

    /**
     * 过滤方法
     * @return array
     */
    protected function getFilter()
    {
        $filter = [];
        $filter[] = [
            "term" => [
                'is_delete' => 0
            ]
        ];

        $filter[] = [
            "terms" => [
                'store_id' => $this->storeIds
            ]
        ];

        return $filter;
    }
}
